import {message} from "@/Hooks/Element-plus"
import axios from "axios"
import type {Method, AxiosRequestConfig} from "axios"
import {GETTOKEN, REMOVETOKEN} from "./local"
import {ElMessage} from "element-plus"
import {useRouter} from "vue-router"
import {$t} from "@/utils/i18n";
import {useSettingStore} from "@/stores/modules/setting";
import {useUserStore} from "@/stores/modules/user";

const router = useRouter()

const service = axios.create({
    baseURL: import.meta.env.VITE_BASE_URL,
    timeout: 5000,
})
// 请求拦截器
service.interceptors.request.use((config) => {
    //令牌
    if (GETTOKEN()) {
        config.headers.Authorization = "Bearer " + GETTOKEN()

        //用户ID
        const {userinfo} = useUserStore();
        if (userinfo.userId) {
            config.headers.UID = userinfo.userId;
        }
    }

    //语言
    const {getLangAlias} = useSettingStore();
    config.headers.Lang = getLangAlias();

    return config
})
// 必须先拦截一下
// 响应拦截器
service.interceptors.response.use(
    (response) => {
        if (response.data.code == 401 || response.data.code == 203) {
            REMOVETOKEN()
            // router.push({path: "/login", replace: true})
            location.reload();
            return Promise.reject(new Error($t('messageBox.loginError')))
        }
        if (response.data.code === 200 || response.headers.success === "true") {
            if (response.headers.msg) {
                response.data.msg = decodeURI(response.headers.msg)
            }
            response.data.success = true
            return response.data
        } else {
            ElMessage({
                showClose: true,
                message: response.data.msg || decodeURI(response.headers.msg),
                type: "error",
            })
            return response.data.msg ? response.data : response
        }
        // return response.data
    },
    (err) => {
        console.log(err.response?.status)
        if (err.response?.status == 424) {
            REMOVETOKEN()
            // router.push({path: "/login", replace: true})
            location.reload()
            return Promise.reject(new Error($t('messageBox.loginError')))
        }
        message("error", $t('messageBox.networkError', {code: err.response?.status || 404}))
        return Promise.reject(new Error(err))
    },
)
type Data<T> = {
    code: string
    msg: string
    message?: string
    success?: boolean
    data: T
}
const request = <T>(
    url: string,
    method: Method = "get",
    data?: object | string,
    config?: AxiosRequestConfig,
) => {
    return service.request<T, Data<T>>({
        url,
        method,
        [method.toLowerCase() === "get" ? "params" : "data"]: data,
        ...config,
    })
}
export default request
